package com.dingyx.ps.task;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * @author dingyuxin
 *
 */
@Slf4j
//@Service
public abstract class PostStationRequest {

    private String ltcURL = "https://open.zxkj.pub/service";

    private String secret = "RDvL26jYjRwEpb6qZG8L";

    String version = "v1";

    String customerId = "vuYPuSnnKLwd6oZAnaZc";

    public String openApiMethod(Map<String, Object> params){
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("version", version);
            paramMap.put("customer_id", customerId);
            for (Map.Entry<String, Object> en : params.entrySet()){
                paramMap.put(en.getKey(), en.getValue());
            }
            // paramMap的Keys按照ASCII排序
            paramMap.put("sign", getSignToken(paramMap));
            log.info("准备传递参数 -> {} 请求地址->{}", JSONObject.toJSONString(paramMap), ltcURL);
            HttpResponse response = HttpRequest.post(ltcURL).body(JSONObject.toJSONString(paramMap)).execute();
            log.info("传递参数结果:{}", response.getStatus());
            String body = response.body();
            log.info("返回的结果{}", body);
            return body;
        }catch (Exception e){
            e.printStackTrace();
            return ExceptionUtil.getMessage(e);
        }
    }


    /**
     * 生成签名
     * @param map
     * @return
     */
    public String getSignToken(Map<String, Object> map) {
        String result = "";
        try {
            List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Object>>() {
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    List<String> ignoreKeys = Arrays.asList("sign", "skus", "cards", "days");
                    if (ignoreKeys.contains(key)){
                        continue;
                    }
                    Object val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            result = sb.toString();
            result=result.replace("[","").replace("]","").replace("'","").replace(',','&').replace(" "  ,"");
            result = result + "key=" + secret;
            // 256加密
            log.info("准备加密的字符串: {}", result);
            Digester sha256 = new Digester(DigestAlgorithm.MD5);
            result = sha256.digestHex(result);
        } catch (Exception e) {
            return null;
        }
        return result;
    }
}
